// pages/phone-verify/phone-verify.js
const { phoneLogin, sendSmsCode } = require('../../utils/auth.js')
const { showError, showSuccess, validatePhone } = require('../../utils/util.js')

Page({
  data: {
    phone: '',
    verificationCode: '',
    codeSending: false,
    countdown: 0,
    step: 1, // 1: 输入手机号, 2: 输入验证码
    codeTimer: null
  },

  onLoad(options) {
    // 如果从登录页传入手机号
    if (options.phone) {
      this.setData({
        phone: options.phone,
        step: 2
      })
      // 自动发送验证码
      this.sendVerificationCode()
    }
  },

  onUnload() {
    // 清理定时器
    if (this.data.codeTimer) {
      clearInterval(this.data.codeTimer)
    }
  },

  /**
   * 手机号输入
   */
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  /**
   * 验证码输入
   */
  onCodeInput(e) {
    this.setData({
      verificationCode: e.detail.value
    })
  },

  /**
   * 下一步 - 发送验证码
   */
  nextStep() {
    const { phone } = this.data
    
    if (!validatePhone(phone)) {
      showError('请输入正确的手机号码')
      return
    }

    this.setData({ step: 2 })
    this.sendVerificationCode()
  },

  /**
   * 上一步 - 返回手机号输入
   */
  prevStep() {
    this.setData({ 
      step: 1,
      verificationCode: '',
      countdown: 0
    })
    
    if (this.data.codeTimer) {
      clearInterval(this.data.codeTimer)
      this.setData({ codeTimer: null })
    }
  },

  /**
   * 发送验证码
   */
  sendVerificationCode() {
    const { phone } = this.data
    
    if (!validatePhone(phone)) {
      showError('请输入正确的手机号码')
      return
    }

    if (this.data.codeSending || this.data.countdown > 0) {
      return
    }

    this.setData({ codeSending: true })

    sendSmsCode(phone).then(() => {
      showSuccess('验证码已发送')
      this.startCountdown()
    }).catch((error) => {
      console.error('发送验证码失败:', error)
      showError('发送验证码失败，请稍后重试')
    }).finally(() => {
      this.setData({ codeSending: false })
    })
  },

  /**
   * 开始倒计时
   */
  startCountdown() {
    let countdown = 60
    this.setData({ countdown })
    
    const timer = setInterval(() => {
      countdown--
      this.setData({ countdown })
      
      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({ codeTimer: null })
      }
    }, 1000)
    
    this.setData({ codeTimer: timer })
  },

  /**
   * 验证登录
   */
  handleVerifyLogin() {
    const { phone, verificationCode } = this.data
    
    if (!validatePhone(phone)) {
      showError('手机号码格式不正确')
      return
    }
    
    if (!verificationCode) {
      showError('请输入验证码')
      return
    }
    
    if (verificationCode.length !== 6) {
      showError('验证码应为6位数字')
      return
    }

    phoneLogin(phone, verificationCode).then((data) => {
      showSuccess('验证成功')
      this.redirectAfterLogin()
    }).catch((error) => {
      console.error('验证失败:', error)
      showError('验证码错误或已过期')
    })
  },

  /**
   * 登录后重定向
   */
  redirectAfterLogin() {
    const { redirectAfterLogin } = require('../../utils/router.js')
    redirectAfterLogin()
  },

  /**
   * 返回登录页
   */
  backToLogin() {
    wx.navigateBack()
  }
})